<template>
  <div ref="pageComBox" class="NewCustomer page_wrapper">
    <div ref="otherBox">
    <Params ref="params" remark-count @search="customerPublicPage" />

    <!-- <el-row type="flex" justify="space-between" class="mb-3">
      <el-col :xs="12">
        <el-button type="primary" size="small" :loading="assistLoading" :disabled="assistDisabled" @click="assistHandle">分配</el-button>
      </el-col>
    </el-row> -->

    <!-- 操作区域 开始 -->
    <div class="link_groups">
      <div>
        <el-button
          type="primary"
          size="small"
          :disabled="assistDisabled"
          @click="receiveCustomer"
          >领取</el-button
        >
        <el-button
          type="primary"
          size="small"
          :loading="assistLoading"
          :disabled="assistDisabled"
          @click="assistHandle"
          >分配</el-button
        >
        <template v-if="userInfo.roleName == '总经理'">
          <el-button
            type="primary"
            size="small"
            :disabled="assistDisabled"
            @click="removeCustomer"
            >删除</el-button
          >
          <el-button type="primary" size="small" @click="openDialog"
            >导入</el-button
          >
        </template>
        <el-radio-group class="el_radio_group" v-model="isNew" @input="onFilterChange">
          <el-radio label="">全部</el-radio>
          <el-radio label="1">新客户</el-radio>
          <el-radio label="2">再分配客户</el-radio>
          <el-radio label="3">历史客户</el-radio>
        </el-radio-group>
      </div>
    </div>
    <!-- 操作区域 end -->
  </div>

    <el-table
    ref="multipleTable"
      :data="dataList"
      style="width: 100%"
      :row-class-name="$getTableClass"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      element-loading-text="加载中..."
      @sort-change="sortChange"
      :max-height="tableHeight"
      :key="tableHeight"
      v-tabscroll="$getTableHeight"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="客户信息" width="140">
        <template slot-scope="{ row }">
          <tab-user :user="row" :list="dataList" v-if="row"></tab-user>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" :width="sortTdWidth">
      </el-table-column>
      <el-table-column prop="media" label="媒体" :width="sortTdWidth">
      </el-table-column>
      <el-table-column label="状态" :width="sortTdWidth">
        <template slot-scope="{ row }">
          {{ showFollowProcess(row.progress) }}
        </template>
      </el-table-column>
      <el-table-column label="锁定状态" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            type="danger"
            class="tab_el_tag"
            size="mini"
            v-if="row.lock == 1"
            >锁定</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="employee.name" label="持有人" :width="80">
      </el-table-column>
      <!-- <el-table-column label="通话状态" width="80">
        <template slot-scope="{row}">
          {{PASSOPTIONSSTATUSLIST[row.call]}}
        </template>
      </el-table-column> -->
      <el-table-column label="客户标签" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            v-for="(item, index) in getTagList(row.label)"
            class="tab_el_tag"
            size="mini"
            :key="index"
            >{{ item }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="公共池" :width="80">
        <template slot-scope="{row}">
          <public-poll :id="row.publicPool" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="条件备注" :width="tdWidth">
        <template slot-scope="{ row }">
          <condition-remark :list="getTagList(row.remark, ';')" />
        </template>
      </el-table-column>
      <el-table-column label="跟进记录" :width="longTdWidth">
        <template slot-scope="scope">
          <el-popover placement="left-end" trigger="hover" width="500">
            <div class="remarkBox">
              <div class="remarkList">
                <div
                  class="item mb-3"
                  v-for="(item, index) in scope.row.remarkList"
                  :key="index"
                >
                  <div class="remark">{{ item.remark }}</div>
                  <div class="createBy pl-3">{{ item.createBy }}</div>
                  <div class="updateDate ml-3">{{ item.updateDate }}</div>
                </div>
              </div>
            </div>
            <div class="remarkList" slot="reference">
              <div
                class="item"
                :class="{ hide: index > 2 }"
                v-for="(item, index) in scope.row.remarkList"
                :key="index"
              >
                <div class="remark">{{ cutWordLength(item.remark,'17')  }}</div>
                <div class="createBy pl-3">{{ item.createBy }}</div>
                <div class="updateDate ml-3">{{ item.updateDate }}</div>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未跟进时间" :width="tdWidth">
        <template slot-scope="scope">
          <div class="red">{{ scope.row.days }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createDate" label="最后备注日期" :width="tdWidth" />
      <el-table-column prop="createDate" label="入库时间" :width="tdWidth" />
      <el-table-column prop="distributeDate" label="分配日期" :width="tdWidth" /> -->
      <el-table-column
        prop="remarkDate"
        label="最后备注日期"
        sortable="remark_date"
        :width="tdWidth"
      />
      <el-table-column
        prop="createDate"
        label="入库时间"
        sortable="create_date"
        :width="tdWidth"
      />
      <el-table-column
        prop="distributeDate"
        label="分配时间"
        sortable="distribute_date"
        :width="tdWidth"
      />
    </el-table>

    <BasePagination
      v-model="page"
      :total="totalCount"
      :pageSize="pageSize"
      @change="pageOnChange"
    />
    <el-dialog
      title="分配"
      width="30%"
      :visible.sync="chooseDialogVisi"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="门店">
          <el-select
            v-model="shopId"
            @change="shopSelectChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in shopOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队">
          <el-select
            v-model="teamId"
            :loading="teamSelectLoading"
            @change="teamSelectChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in teamOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工">
          <el-select
            v-model="employeeId"
            :loading="employeeSelectLoading"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in employeeOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chooseDialogVisi = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="assistSubmitLoading"
          @click="assistSubmit"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <!-- 批量导入 开始 -->
    <glsx-dialog
      :show="importDialog"
      title="批量导入"
      width="600px"
      @close="closeDialog('importDialog')"
    >
      <div class="upload_box">
        <div class="cell" v-if="!isSuccess">
          <div class="name"><span class="cred">*</span>选择要导入的名单：</div>
          <div class="txt">
            <el-input
              v-model="uploadInfo.name"
              class="a_input"
              size="small"
              readonly
            ></el-input>
            <el-upload
              class="el_upload"
              ref="upload"
              :headers="uploadHeader"
              :accept="fileAccept"
              :action="CUSTOMER_IMPORT_FILE"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="onFileChange"
              :on-success="onSuccess"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取文件</el-button
              >
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="submitUpload"
                >上传</el-button
              >
            </el-upload>
          </div>
          <!-- <a :href="DOWNLOAD_CUSTOMER_MODULEFILE" class="module_link">模板下载</a> -->
          <el-link type="primary" class="module_link" @click="downDocFile()">
            模板下载
          </el-link>
        </div>

        <div class="success_tips" v-if="isSuccess">
          <i class="el-icon-circle-check icon"></i>
          <template v-if="!uploadSuccessInfo">
            <span>成功导入</span>
          </template>
          <template v-else>
            <span>失败客户：</span>
            <span class="cred">{{ uploadSuccessInfo }}</span>
          </template>
        </div>
      </div>
    </glsx-dialog>
    <!-- 批量导入 end -->
  </div>
</template>

<script>
//import Params from "./Params.vue";
import Params from "@/components/common/params.vue";
import {
  customerPublicPage,
  employeeList,
  customerDistribute,
  shopList,
  allTeamList,
  getEmployee,
} from "@/api/customer";
import { followUpOptions, startOptions, passOptions } from "./config";
import { mapState } from "vuex";
import GlsxDialog from "@/components/Dialog";
import FollowUp from "@/components/follow";
import { SEXTYPELIST, PASSOPTIONSSTATUSLIST } from "@/common/constants";
import TabUser from "@/components/user";
import {
  showFollowProcess,
  getTagList,
  showModal,
  showToast,
  received,
} from "@/utils/util";
import {
  CUSTOMER_IMPORT_FILE,
  DOWNLOAD_CUSTOMER_MODULEFILE,
  DELETE_PUBLICPOOL_CUSTOMER,
  GET_PUBLICPOOL_CUSTOMER,
} from "@/http/customer";
import { downPackFile } from "@/utils/common";
export default {
  components: { Params, GlsxDialog, FollowUp, TabUser },
  data() {
    return {
      fieldList: [],
      page: 1,
      pageSize: 100,
      dataList: [],
      totalCount: 0,
      form: {},
      followUpOptions,
      startOptions,
      passOptions,
      value1: "",
      selectItem: {},
      input: "",
      assistLoading: false,
      assistDisabled: true,
      chooseDialogVisi: false,
      updateLoading: false,
      employeeList: [],
      helpEmployeeId: "",
      assistSubmitLoading: false,
      shopId: "",
      teamId: "",
      employeeId: "",
      shopOptionList: [],
      teamOptionList: [],
      employeeOptionList: [],
      teamSelectLoading: false,
      employeeSelectLoading: false,
      sortTdWidth: 56,
      smallWidth: 110,
      tdWidth: 160,
      longTdWidth: 500,
      //showDialog: false,
      SEXTYPELIST,
      showFollowProcess: (str) => showFollowProcess(str),
      getTagList: (str, id) => getTagList(str, id),
      PASSOPTIONSSTATUSLIST,
      userInfo: {},
      importDialog: false,
      uploadInfo: {},
      isSuccess: false,
      fileAccept: ".xlsx,.xls",
      uploadHeader: {},
      uploadSuccessInfo: {},
      CUSTOMER_IMPORT_FILE,
      DOWNLOAD_CUSTOMER_MODULEFILE,
      loading: false,
      isNew: '',
      tableHeight:0
    };
  },
  mounted() {
    this.shopList();
    this.fieldList = JSON.parse(JSON.stringify(this.fieldList1));
    this.userInfo = this.$store.getters.userInfo || {};
    received("update.success", this.customerPublicPage);
    // 计算表格的高度
    let _this = this
    this.$getTableHeight();
    window.onresize = function () {
      _this.$getTableHeight();
    };
  },
  computed: {
    ...mapState({
      fieldList1: (state) => state.myClient.fieldList,
    }),
  },
  watch: {
    fieldList1(val) {
      this.fieldList = JSON.parse(JSON.stringify(val));
    },
  },
  methods: {
    async customerPublicPage(form) {
      console.log("66666666666666");
      try {
        this.showAppLoading();
        this.loading = true;
        await customerPublicPage({
          page: this.page,
          size: this.pageSize,
          paramObject: { ...form },
        }).then((res) => {
          this.loading = false;
          const { data } = res;
          this.dataList = data.dataList || [];
          this.totalCount = data.totalCount;
          this.dataList.forEach((element) => {
            if (element.id === this.selectItem.id) {
              this.selectItem = element;
            }
          });
          this.$nextTick(() => {
            let index = 0;
            const list = document.querySelectorAll("tr");
            const tbody = document.querySelector("tbody");
            const comment = tbody.getElementsByClassName("comment");
            for (let index1 = comment.length - 1; index1 >= 0; index1--) {
              const element = comment[index1];
              element.remove();
            }
            list.forEach((dom) => {
              if (dom.classList.contains("el-table__row")) {
                if (this.dataList[index].comment) {
                  const div = document.createElement("div");
                  div.innerHTML = `主管点评：${this.dataList[index].comment}`;
                  div.classList.add("comment");
                  dom.parentNode.insertBefore(div, dom);
                }
                index++;
              }
            });
          });
        });
        this.hideAppLoading();
      } catch (error) {
        this.hideAppLoading();
      }
    },
    pageOnChange(row) {
      this.page = row.page;
      if (row.pageSize) {
        this.pageSize = row.pageSize;
      }
      this.$refs.params.search();
    },

    handleSelectionChange(e) {
      this.assistDisabled = e.length === 0;
      this.idArr = e.map((element) => element.id);
    },
    select(selection, row) {
      if (selection.length > 1) {
        const del_row = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(del_row, false);
      }
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1;
      }
    },
    async assistHandle() {
      employeeList().then((res) => {
        this.employeeList = res.data;
      });
      this.chooseDialogVisi = true;
    },
    async assistSubmit() {
      this.assistSubmitLoading = true;
      try {
        const form = {
          idList: this.idArr,
          shopId: this.shopId,
          teamId: this.teamId,
          employeeId: this.employeeId,
        };
        await customerDistribute(form).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message);
            this.$refs.params.search();
            this.chooseDialogVisi = false;
          }
        });
        this.assistSubmitLoading = false;
      } catch (error) {
        this.assistSubmitLoading = false;
      }
    },
    shopList() {
      shopList({ type: 1 }).then((res) => {
        this.shopOptionList = res.data;
      });
    },
    async shopSelectChange() {
      this.teamSelectLoading = true;
      this.teamId = "";
      this.employeeId = "";
      try {
        await allTeamList({ shopId: this.shopId, type: 1 }).then((res) => {
          this.teamOptionList = res.data;
        });
        this.teamSelectLoading = false;
      } catch (error) {
        this.teamSelectLoading = false;
      }
    },
    async teamSelectChange() {
      this.employeeSelectLoading = true;
      this.employeeId = "";
      try {
        await getEmployee({
          shopId: this.shopId,
          teamId: this.teamId,
          type: 1,
        }).then((res) => {
          // this.employeeOptionList = res.data.dataList
          this.employeeOptionList = res.data || [];
        });
        this.employeeSelectLoading = false;
      } catch (error) {
        this.employeeSelectLoading = false;
      }
    },

    // 打开导入弹框
    openDialog() {
      this.importDialog = true;
    },

    // 关闭弹框
    closeDialog() {
      this.importDialog = false;
      //this.customerPublicPage();
    },

    // 监听上传文件变化
    onFileChange(file) {
      console.log(file);
      this.uploadInfo = file;
    },

    // 文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },

    // 监听文件导入成功
    onSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.isSuccess = true;
        this.uploadSuccessInfo = response.data;
      }
    },

    // 删除客户
    removeCustomer() {
      let _this = this;
      showModal({
        message: "确定删除该客户吗？",
        showCancelButton: true,
        success: function () {
          let oParams = {};
          oParams.idList = _this.idArr;
          DELETE_PUBLICPOOL_CUSTOMER(oParams).then((res) => {
            if (res.code == 200) {
              showToast({
                message: "删除成功",
                type: "success",
              });
              _this.$refs.params.search();
            }
          });
        },
      });
    },

    // 领取客户
    receiveCustomer() {
      let _this = this;
      showModal({
        message: "确定领取该客户吗？",
        showCancelButton: true,
        success: function () {
          let oParams = {};
          oParams.idList = _this.idArr;
          GET_PUBLICPOOL_CUSTOMER(oParams).then((res) => {
            if (res.code == 200) {
              showToast({
                message: "领取成功",
                type: "success",
              });
              _this.$refs.params.search();
            }
          });
        },
      });
    },

    // 模板下载
    downDocFile() {
      let oParams = {};
      oParams.url = DOWNLOAD_CUSTOMER_MODULEFILE;
      downPackFile(oParams);
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      console.log(column);
      //this.formInline.orderField = prop;
      let str = `${column.sortable} asc`;
      if (order == "ascending") {
        str = `${column.sortable} asc`;
      } else {
        str = `${column.sortable} desc`;
      }
      this.$refs.params.setParams("sort", str);
      this.$refs.params.search();
      //this.getList();
    },

     // 筛选客户
     onFilterChange(e) {
      this.$refs.params.setParams('isNew', e)
      this.$refs.params.search()
    }
  },
};
</script>

<style lang="scss" scoped>
.NewCustomer {
  padding: 20px;
}
.txt {
  padding: 8px 0;
}
.wrapping {
  margin-right: 10px;
  margin-bottom: 10px;
}
.btn {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.upload_box {
  padding: 20px 0 40px 0;

  .cell {
    display: flex;
    align-items: center;

    .name {
      .cred {
        color: #f00;
      }
    }

    .txt {
      display: flex;
      align-items: center;

      .a_input {
        margin-right: 10px;
      }

      .el_upload {
        display: flex;
        align-items: center;
      }
    }
    .module_link {
      margin-left: 10px;
      color: #167fff;
      text-decoration: underline;
    }
  }

  .success_tips {
    display: flex;
    align-items: center;
    justify-content: center;

    .icon {
      font-size: 24px;
      color: #67c23a;
      margin-right: 10px;
    }

    a {
      color: #167fff;
    }
  }
}
.el_radio_group{
  margin-left:10px;
}
</style>
